from django.shortcuts import render
from django.conf import settings
from rest_framework.decorators import api_view, permission_classes
from rest_framework.permissions import IsAuthenticated
from rest_framework.response import Response
from rest_framework import status
from .models import Image
from .serializers import ImageUploadSerializer, ImageSerializer

@api_view(['POST'])
@permission_classes([IsAuthenticated])
def upload_image(request):
    """上传图片"""
    serializer = ImageUploadSerializer(data=request.data)
    if serializer.is_valid():
        # 优先使用MinioClient
        try:
            from .utils import upload_to_minio
            image_file = request.FILES.get('image')
            if image_file:
                image_url = upload_to_minio(
                    image_file, 
                    request.user.id, 
                    serializer.validated_data['image_type']
                )
                
                # 创建图片记录
                image = Image.objects.create(
                    user=request.user,
                    image_type=serializer.validated_data['image_type'],
                    image=image_url,
                    description=serializer.validated_data.get('description', '')
                )
                
                response_serializer = ImageSerializer(image)
                return Response(response_serializer.data, status=status.HTTP_201_CREATED)
        except Exception as e:
            # 如果Minio上传失败，尝试其他存储方式
            print(f"MinIO上传失败: {str(e)}")
        
        # 检查云存储配置
        if settings.OSS_ACCESS_KEY_ID and settings.OSS_ACCESS_KEY_SECRET:
            # 上传到阿里云OSS
            try:
                from .utils import upload_to_oss
                image_file = request.FILES.get('image')
                if image_file:
                    image_url = upload_to_oss(
                        image_file, 
                        request.user.id, 
                        serializer.validated_data['image_type']
                    )
                    
                    # 创建图片记录
                    image = Image.objects.create(
                        user=request.user,
                        image_type=serializer.validated_data['image_type'],
                        image=image_url,
                        description=serializer.validated_data.get('description', '')
                    )
                    
                    response_serializer = ImageSerializer(image)
                    return Response(response_serializer.data, status=status.HTTP_201_CREATED)
            except Exception as e:
                return Response({'error': f'上传失败: {str(e)}'}, status=status.HTTP_500_INTERNAL_SERVER_ERROR)
        
        elif settings.COS_SECRET_ID and settings.COS_SECRET_KEY:
            # 上传到腾讯云COS
            try:
                from .utils import upload_to_cos
                image_file = request.FILES.get('image')
                if image_file:
                    image_url = upload_to_cos(
                        image_file, 
                        request.user.id, 
                        serializer.validated_data['image_type']
                    )
                    
                    # 创建图片记录
                    image = Image.objects.create(
                        user=request.user,
                        image_type=serializer.validated_data['image_type'],
                        image=image_url,
                        description=serializer.validated_data.get('description', '')
                    )
                    
                    response_serializer = ImageSerializer(image)
                    return Response(response_serializer.data, status=status.HTTP_201_CREATED)
            except Exception as e:
                return Response({'error': f'上传失败: {str(e)}'}, status=status.HTTP_500_INTERNAL_SERVER_ERROR)
        else:
            # 上传到本地
            try:
                from .utils import upload_to_local
                image_file = request.FILES.get('image')
                if image_file:
                    file_path = upload_to_local(
                        image_file, 
                        request.user.id, 
                        serializer.validated_data['image_type']
                    )
                    
                    # 更新序列化器数据
                    serializer.validated_data['image'] = file_path
                    
                    # 设置用户并保存
                    image = serializer.save(user=request.user)
                    
                    response_serializer = ImageSerializer(image)
                    return Response(response_serializer.data, status=status.HTTP_201_CREATED)
            except Exception as e:
                return Response({'error': f'上传失败: {str(e)}'}, status=status.HTTP_500_INTERNAL_SERVER_ERROR)
    
    return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST)


@api_view(['GET'])
@permission_classes([IsAuthenticated])
def get_user_images(request):
    """获取用户图片列表"""
    image_type = request.GET.get('type', None)
    
    if image_type:
        images = Image.objects.filter(user=request.user, image_type=image_type)
    else:
        images = Image.objects.filter(user=request.user)
    
    serializer = ImageSerializer(images, many=True)
    return Response(serializer.data)


@api_view(['DELETE'])
@permission_classes([IsAuthenticated])
def delete_image(request, image_id):
    """删除图片"""
    try:
        image = Image.objects.get(id=image_id, user=request.user)
    except Image.DoesNotExist:
        return Response({'error': '图片不存在'}, status=status.HTTP_404_NOT_FOUND)
    
    # 删除图片文件
    if image.image:
        image.image.delete()
    
    # 删除数据库记录
    image.delete()
    
    return Response({'message': '删除成功'}, status=status.HTTP_204_NO_CONTENT)